package com.zjp.bean;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class BeanUtils {


    /**
     *
     * 相同类型的两个对象比较属性值，得到不同属性的名称和对应的值
     * @param o1     对象1
     * @param o2     对象2
     * @param isSame 是否相同
     * @return 字段名集合
     */
    public <T> List<String> getObjField(T o1, T o2, boolean isSame) {

        if (Objects.isNull(o1) || Objects.isNull(o2)) {
            return null;
        }
        List<String> textList = new ArrayList<>();
        try {
            Class<?> clazz = o1.getClass();
            Field[] fields = o1.getClass().getDeclaredFields();
            for (Field field : fields) {
                if (Modifier.isFinal(field.getModifiers())) {
                    continue;
                }
                String fieldName = field.getName();
                PropertyDescriptor pd = new PropertyDescriptor(fieldName, clazz);
                Method getMethod = pd.getReadMethod();
                Object value1 = getMethod.invoke(o1);
                Object value2 = getMethod.invoke(o2);
                String s1 = value1 == null ? "" : value1.toString();//避免空指针异常
                String s2 = value2 == null ? "" : value2.toString();//避免空指针异常
                if (s1.equals(s2)) {
                    System.out.println("一样的属性：" + fieldName + " 属性值：[" + s1 + "," + s2 + "]");
                    if (isSame) {
                        textList.add(fieldName);
                    }
                } else {
                    System.out.println("不一样的属性：" + fieldName + " 属性值：[" + s1 + "," + s2 + "]");
                    if (!isSame) {
                        textList.add(fieldName);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (isSame) {
            System.out.println("===获取相同属性字段===");
        } else {
            System.out.println("===获取不同属性字段===");
        }
        textList.forEach(System.out::println);
        return textList;
    }
}
